<template lang="pug">
  el-dialog(v-bind:visible="visible"
  v-bind:before-close="close"
  v-bind:close-on-click-modal="false"
  v-bind:append-to-body="true"
  width="500px"
  )
    div.tit(slot="title") 用户注册
    el-form.form(ref="dialogForm" v-bind:model="formModel")
      el-form-item(label="" prop="phone" v-bind:rules="rules.phone")
        el-input(v-model="formModel.phone" placeholder="手机号码(可使用手机号登录)")
      el-form-item(label="" prop="img_code" v-bind:rules="rules.img_code")
        div.s-flex
          el-input.s-flex_item(v-model="formModel.img_code" placeholder="验证码")
          img.img-code(v-bind:src="random" v-on:click="getRandomImg")
      el-form-item(label="" prop="smsNumber" v-bind:rules="rules.smsNumber")
        div.s-flex
          el-input.s-flex_item(v-model="formModel.smsNumber" placeholder="短信验证码")
          el-button.btn-sendSMS(v-on:click="onSendSMS" size="small" type="primary") {{sendSMSText}}
      el-form-item(label="" prop="password" v-bind:rules="rules.password")
        el-input(v-model="formModel.password" type="password" placeholder="新密码（6-16个字符）")
      el-form-item(label="" prop="repassword" v-bind:rules="rules.repassword")
        el-input(v-model="formModel.repassword" type="password" placeholder="确认密码")
      div
        el-button.btn-register(v-on:click="onRegister" type="primary") 立即注册
</template>
<script type="text/ecmascript-6">
  import {baseURL} from '../../config/global.toml'

  export default {
    name: 'SignUp',
    data() {
      const validateTel = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入用户手机号！'))
        }
        if (!(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(value))) {
          callback(new Error('请输入正确的手机号!'))
        }
        callback()
      }
      const validateImgCode = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入图形验证码'))
        } else {
          console.log('this.randomMessage', this.randomMessage)
          if (this.randomMessage !== '') {
            callback(new Error(this.randomMessage))
            this.randomMessage = ''
          } else {
            callback()
          }
        }
      }
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          if (!(/^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S{6,16}$/.test(value))) {
            callback(new Error('密码需要由字母，数字和符号两种或以上组合！'))
          } else {
            if (this.formModel.repassword !== '') {
              this.$refs.dialogForm.validateField('repassword')
            }
            callback()
          }
        }
      }
      const validateRepass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.formModel.password) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      const validateVerify = (rule, value, callback) => {
        console.log('validateVerify', this.isClickRegister)
        if (this.isClickRegister) {
          if (value === '') {
            callback(new Error('请输入短信验证码！'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
      return {
        visible: false,
        random: '',
        randomMessage: '',
        smsFlag: true,
        sendSMSText: '获取短信验证码',
        isClickRegister: false, // 是否点击了注册按钮
        formModel: {
          phone: '',
          img_code: '',
          smsNumber: '',
          password: '',
          repassword: ''
        },
        rules: {
          phone: [{validator: validateTel, trigger: 'blur'}],
          img_code: [{validator: validateImgCode, trigger: 'blur'}],
          password: [{validator: validatePass, trigger: 'blur'}],
          repassword: [{validator: validateRepass, trigger: 'blur'}],
          smsNumber: [{validator: validateVerify, trigger: 'blur'}]
        }
      }
    },
    mounted() {
      this.getRandomImg()
    },
    methods: {
      open() {
        this.visible = true
      },
      getRandomImg() {
        this.icode = Math.random()
        this.random = `${baseURL}/webapp/user/imgCode?iCode=${this.icode}`
      },
      onSendSMS() {
        if (this.smsFlag) {
          // 验证电话号码
          let telFlag = false
          this.$refs.dialogForm.validateField('phone', err => {
            telFlag = !err
          })
          // 验证图形验证码
          let imgCodeFlag = false
          this.$refs.dialogForm.validateField('img_code', err => {
            imgCodeFlag = !err
          })
          if (telFlag && imgCodeFlag) {
            this.randomMessage = ''
            this.$http.request({
              method: 'POST',
              url: `/webapp/user/smsSend`,
              params: {
                phone: this.formModel.phone,
                imgCode: this.formModel.img_code,
                iCode: this.icode
              }
            }).then(res => {
              console.log('res', res)
              if (res.data.success) {
                this.$message.success(res.data.message)
                this.smsFlag = false
                let m = 59
                let jiShi = setInterval(() => {
                  this.sendSMSText = `${m}秒后可再次发送`
                  m--
                  if (m <= 1) {
                    this.smsFlag = true
                    this.sendSMSText = `重新获取短信验证码`
                    clearInterval(jiShi)
                  }
                }, 1000)
              } else {
                this.randomMessage = res.data.message
                this.getRandomImg()
                this.$refs.dialogForm.validateField('img_code')
              }
            })
          }
        }
      },
      onRegister() {
        this.isClickRegister = true
        this.$refs.dialogForm.validate((valid) => {
          this.isClickRegister = false
          if (valid) {
            console.log('valid', valid)
            this.$http.request({
              method: 'POST',
              url: `/webapp/user/register`,
              params: {
                phone: this.formModel.phone,
                code: this.formModel.smsNumber,
                password: this.formModel.password
              }
            }).then(res => {
              console.log('res', res)
              if (res.data.success) {
              }
            })
          }
        })
      },
      close() {
        this.visible = false
      }
    }
  }
</script>
<style scoped lang="stylus" type="text/stylus">
  .tit
    text-align center
  .form
    width 300px
    margin 0 auto
    .s-flex
      align-items center
    .img-code
      width 100px
      margin-left 15px
    .btn-sendSMS
      margin-left 15px
    .btn-register
      width 100%
</style>
